#! /usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
from datetime import timedelta

from flask import flash
from flask import redirect
from flask import url_for
from flask import request
from flask import Blueprint
from flask import render_template
from flask_login import login_required

from app import db, app
from app import global_params
from app.models import Client, Loan


bp = Blueprint("users", __name__, template_folder="template",
               static_folder="static")


@bp.route('/preloan/index', methods=['GET', 'POST'])
@login_required
def preloan_index():

    mobile = request.args.get('mobile', "")
    cname = request.args.get('cname', "")
    entry = request.args.get("entry", 0, int)
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    status = request.args.get("status", -1, int)
    offset = request.args.get('offset', 0, int)
    limit = request.args.get('limit', 20, int)

    query = Loan.query.join(Client, Loan.client_id == Client.id)
    if mobile:
        query = query.filter(Client.mobile.like("%" + mobile + "%"))
    if cname:
        query = query.filter(Client.username.like("%" + cname + "%"))
    if start_time:
        query = query.filter(Loan.start_time >= start_time)
    if end_time:
        my_end_time = end_time + " 23:59:59"
        query = query.filter(Loan.start_time < my_end_time)
    if status >= 1:
        query = query.filter(Loan.status == status)
    if entry:
        query = query.filter(Loan.entry == entry)

    count = query.count()
    loans = query.order_by(
        Loan.create_time.desc()
    ).order_by(Loan.id.desc()).offset(offset).limit(limit).all()

    return render_template('users/preloan_index.html', loans=loans,
                           start_time=start_time,
                           end_time=end_time, mobile=mobile, cname=cname,
                           offset=offset, status=status, limit=limit,
                           count=count, entry=entry)


@bp.route('/loaned/index', methods=['GET', 'POST'])
@login_required
def loaned_index():

    mobile = request.args.get('mobile', "")
    cname = request.args.get('cname', "")
    entry = request.args.get("entry", 0, int)
    l_end = request.args.get("l_end", 1, int)
    start_time = request.args.get('start_time')
    end_time = request.args.get('end_time')
    offset = request.args.get('offset', 0, int)
    limit = request.args.get('limit', 20, int)

    query = Loan.query.join(Client, Loan.client_id == Client.id)

    if mobile:
        query = query.filter(Client.mobile.like("%" + mobile + "%"))
    if cname:
        query = query.filter(Client.username.like("%" + cname + "%"))
    if start_time:
        query = query.filter(Loan.start_time >= start_time)
    if end_time:
        my_end_time = end_time + " 23:59:59"
        query = query.filter(Loan.start_time < my_end_time)
    if l_end == 1:
        end = (0, 2)
        query = query.filter(Loan.end.in_(end))

    if entry:
        query = query.filter(Loan.entry == entry)

    count = query.count()
    loans = query.order_by(
        Loan.create_time.desc()).order_by(Loan.id.desc()).offset(
        offset).limit(limit).all()

    return render_template('users/loaned_index.html', loans=loans,
                           start_time=start_time,
                           end_time=end_time, mobile=mobile, cname=cname,
                           offset=offset, l_end=l_end, limit=limit,
                           count=count, entry=entry)


@bp.route("/force/index")
@login_required
def force_loan_index():
    today = datetime.now().strftime("%Y-%m-%d")
    mobile = request.args.get('mobile', "")
    cname = request.args.get('cname', "")
    entry = request.args.get("entry", 0, int)
    start_time = request.args.get('start_time', today)
    end_time = request.args.get('end_time', today)
    offset = request.args.get('offset', 0, int)
    limit = request.args.get('limit', 20, int)

    end = (0, 2)  # 贷款中，逾期为还
    query = Loan.query.join(Client, Loan.client_id == Client.id)
    query = query.filter(Loan.end.in_(end))

    if mobile:
        query = query.filter(Client.mobile.like("%" + mobile + "%"))
    if cname:
        query = query.filter(Client.username.like("%" + cname + "%"))
    if start_time:
        query = query.filter(Loan.end_time >= start_time)
    if end_time:
        my_end_time = end_time + " 23:59:59"
        query = query.filter(Loan.end_time < my_end_time)
    if entry:
        query = query.filter(Loan.entry == entry)

    count = query.count()
    loans = query.order_by(Loan.id.desc()).offset(offset).limit(limit).all()

    return render_template("users/force_loan_index.html",
                           start_time=start_time, end_time=end_time,
                           cname=cname, mobile=mobile, offset=offset,
                           limit=limit, count=count, loans=loans, entry=entry)


@bp.route('/client/index', methods=['GET', 'POST'])
@login_required
def client_index():

    icloud = request.args.get("icloud", "")
    mobile = request.args.get("mobile", "")
    offset = request.args.get('offset') or 0
    limit = request.args.get('limit') or 20

    query = Client.query
    if icloud:
        query = query.filter(Client.icloud.like("%" + icloud + "%"))
    if mobile:
        query = query.filter(Client.mobile.like("%" + mobile + "%"))

    count = query.count()
    clients = query.offset(offset).limit(limit).all()
    return render_template('users/client_index.html', clients=clients,
                           mobile=mobile, icloud=icloud, offset=offset,
                           count=count,
                           limit=limit)


@bp.route('/client/create', methods=['POST'])
@login_required
def client_create():
    icloud = request.form.get('icloud')
    icloud_pw = request.form.get('icloud_pw')
    account = request.form.get('account')
    username = request.form.get('username')
    mobile = request.form.get('mobile')
    comment = request.form.get('comment', '')
    user = Client.query.filter_by(icloud=icloud)
    if user.count():
        flash(u"客户已经存在", category='danger')
        return redirect(url_for('users.client_index'))
    c = Client(icloud=icloud, icloud_pw=icloud_pw, account=account,
               username=username, mobile=mobile, comment=comment)
    db.session.add(c)
    db.session.commit()
    flash(u'创建客户成功', category='success')
    return redirect(url_for('users.client_index'))


@bp.route('/loan/create', methods=["POST"])
@login_required
def loan_create():

    # user_info
    username = request.form.get("username")
    mobile = request.form.get("mobile")
    icloud = request.form.get("icloud", "")
    icloud_pw = request.form.get("icloud_pw", "")

    money = request.form.get('money', type=float)
    commission = request.form.get('commission', type=float)
    start_time = request.form.get('start_time')
    entry = request.form.get('entry', type=int)  # 入口 1 线上 2 线下
    iphone = request.form.get('iphone')
    status = request.form.get('status', 1, type=int)  # 1 申请 2 贷款中 3 续借
    end = request.form.get('end', 0, type=int)  # 0 否1 是
    channel = request.form.get('channel', type=int)  # 1 支付宝 2 微信 3 转账
    comment = request.form.get('comment', "")
    try:
        client = Client.query.filter_by(
            username=username, mobile=mobile).one_or_none()
        if client is None:
            client = Client(username=username, mobile=mobile, icloud=icloud,
                            icloud_pw=icloud_pw)
            db.session.add(client)
        elif icloud or icloud_pw:
            if icloud:
                client.icloud = icloud
            if icloud_pw:
                client.icloud_pw = icloud_pw
            db.session.add(client)

        start_time = datetime.strptime(start_time, "%Y-%m-%d")
        end_time = start_time + timedelta(days=global_params.NORMAL_DELTA_DAYS)
        create_time = datetime.now()
        l = Loan(money=money, commission=commission, start_time=start_time,
                 end_time=end_time, iphone=iphone, status=status, end=end,
                 entry=entry, create_time=create_time,
                 channel=channel, comment=comment, client=client)
        db.session.add(l)
        db.session.commit()
        flash(u"创建贷款成功", "success")
        return redirect(url_for('users.preloan_index'))

    except Exception as e:
        db.session.rollback()
        app.logger.info(str(e))
        flash(u"无法创建贷款", "danger")
        return redirect(url_for('users.preloan_index'))
